package cn.maihe.elg.operation.service.guarantee;

import cn.maihe.elg.operation.config.TemplateUploadConfig;
import cn.maihe.elg.operation.model.vo.guarantee.TemplateVO;
import cn.maihe.elg.operation.repository.entity.GuaranteeTemplateDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeTemplateVo;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.framework.starter.base.sql.PageBo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @Description 保函电子模板服务
 * @Author WJH
 * @Date 2021/03/25
 */
@Service
public class GuaranteeTemplateService extends BaseDaoService<GuaranteeTemplateDO> {

    @Resource
    private TemplateUploadConfig templateUploadConfig;

    public PageBo<TemplateVO> selectPageBySql(int pageNo, int pageSize, String gmtCreateRange, GuaranteeTemplateVo vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        if (StringUtils.isNotBlank(gmtCreateRange)) {
            String[] rangeAy = gmtCreateRange.split(",");
            if (rangeAy.length > 1) {
                paramsMap.put("startGmtCreate", rangeAy[0] + " 00:00:00");
                paramsMap.put("endGmtCreate", rangeAy[1] + " 23:59:59");
            }
        }
        return this.selectPageBySql("selectTemplateList", "selectTemplateCount", paramsMap, pageNo, pageSize);
    }

    public Path getTemplatePath(Long id) {
        try {
            GuaranteeTemplateDO templateDO = this.selectById(id);
            if (templateDO != null && templateDO.getContent() != null) {
                JSONObject content = JSON.parseObject(templateDO.getContent());
                String name = content.getString("name");
                String url = content.getString("url");
                Path path = Paths.get(templateUploadConfig.getPath(), url);
                if (Files.notExists(path)) {
                    throw new RuntimeException("保函模板文件[" + name + "]不存在");
                }
                return path;
            } else {
                throw new RuntimeException("查无此申请订单Id记录或保函模板文件未上传");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("申请订单Id获取保函模板文件异常:" + e.getMessage(), e);
        }
    }

}
